;;; *************************************************************************
;;;; FILE IDENTIFICATION
;;;;
;;;; Name:          tools.lisp
;;;; Purpose:       Some tools for the Audioscrobbler/lastfm wrapper
;;;; Programmer:    Nicolas Lamirault <nicolas.lamirault@gmail.com>
;;;;
;;;; This file, part of audioscrobbler, is Copyright (c) 2007 by Nicolas Lamirault
;;;;
;;;; cl-audioscrobbler users are granted the rights to distribute and use this software
;;;; as governed by the terms of the MIT License :
;;;; http://www.opensource.org/licenses/mit-license.php
;;;;
;;;; *************************************************************************


(in-package :cl-audioscrobbler)


(defun get-date-formated (control-string)
  "Get current date in CONTROL-STRING format."
 (multiple-value-bind
       (second minute hour date month year day-of-week dst-p tz)
     (decode-universal-time (get-universal-time) 0) ;;(get-decoded-time)
   (declare (ignore day-of-week dst-p tz))
   (format nil control-string
           year month date hour minute second)))


(defun get-current-date ()
  "Get current date in YYYY-MM-DD hh:mm:ss format."
  (get-date-formated "~2,'0d-~2,'0d-~2,'0d ~2,'0d:~2,'0d:~2,'0d"))


(defun get-timestamp ()
  "Get current date in YYYYMMDDHHMMSS format."
  (get-date-formated "~A~2,'0d~2,'0d~2,'0d~2,'0d~2,'0d"))


(defun unix-timestamp ()
  "Get the Unix timestamp : seconds since Jan 01 1970."
  (- (get-universal-time) (encode-universal-time 0 0 1 1 1 1970)))


(defun perform-audioscrobbler (query)
  "Retreive informations from Audioscrobbler Web Service."
  (when *debug*
    (format t "Audioscrobbler query : ~A~%" query))
  (multiple-value-bind (body status-code headers uri stream must-close)
      (drakma:http-request query)
    (declare (ignore headers uri stream must-close))
    (when (and status-code (= status-code 200))
      body)))


(defun get-xml-answer (query)
  "Make a request to the Audioscrobbler Web Service, and parse XML output."
  (let ((content (perform-audioscrobbler query)))
    (when content 
      (s-xml:parse-xml-string content))))


